package cn.edu.dlut.ssdut.foodCredit2012.service;

/*import java.util.List;

import org.hibernate.Query;*/
import org.hibernate.Session;

import cn.edu.dlut.ssdut.foodCredit2012.model.PermissionCollection;
import cn.edu.dlut.ssdut.foodCredit2012.util.HibernateUtil;

public class PermissionCollectionService {
	
	public void add(PermissionCollection p) throws Exception{
		if(!hasPermission(p)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.save(p);
			session.getTransaction().commit();
		}
	}
	
	public void delete(PermissionCollection p) throws Exception {
		if(hasPermission(p)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.delete(p);
			session.getTransaction().commit();
		}
	}
	
	public void update (PermissionCollection p)throws Exception {
		if(hasPermission(p)){
			Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.update(p);
			session.getTransaction().commit();
		}
	}
	
	/*public List permissionList() {
		List permissionList = null;
		Session session = HibernateUtil.getUserSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Query query = session.createQuery("from Permission");
		query.setFirstResult(2);
		query.setMaxResults(10);
		permissionList = query.list();
		
		session.getTransaction().commit();
		
		return permissionList;
	}*/
	
	public boolean hasPermission(PermissionCollection p) throws Exception {
		Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
		session.beginTransaction();
		long count = (Long)session.createQuery("select count(*) from PermissionCollection p where p.licenceID = :licenceID")
			.setString("licenceID", p.getLicenceID())
			.uniqueResult();
		session.getTransaction().commit();
		
		if(count > 0) return true;
		return false;
		
	}
	
	public PermissionCollection load(PermissionCollection p) throws Exception{
		if(hasPermission(p)){
			p = loadByLicenceID(p.getLicenceID());
			return p;
		}
		return p;
	}
	
	public PermissionCollection loadByLicenceID(String licenceID) throws Exception{
		PermissionCollection p = new PermissionCollection();
		Session session = HibernateUtil.getCollectionSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		p = (PermissionCollection)session.createQuery("select p from PermissionCollection p where p.licenceID = :licenceID")
			.setParameter("licenceID", licenceID)
			.uniqueResult();
		
		session.getTransaction().commit();
		return p;
	}

}
